package pass;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class myTimer {
	private static boolean timerSwitch = true;
	private static boolean timerSwitchPerDay = true;
	private static boolean timerSwitchPerWeek = true;

	/**
	 * 定时器
	 * 
	 * @param args
	 */
	public static void main(String args[]) {
		myTimer mt = new myTimer();
		mt.runAuto();
		mt.runPerDay();
		mt.runPerWeek();
	}

	/**
	 * 定时器 每天
	 */
	public void runPerDay() {
		if (!timerSwitchPerDay)
			return;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String today = sdf.format(new Date());
		Date d = null;
		try {
			d = sdf.parse(today);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		long todayMill = d.getTime() + 3600000;// 凌晨1点
		long period = 86400000;// 间隔一天
		Timer timer = new Timer();
		if (System.currentTimeMillis() > todayMill) {// 明天运行
			todayMill = todayMill + period;
		}
		// System.out.println(new Date(todayMill));

		timer.scheduleAtFixedRate(new TimerTask() {
			int i = 0;

			public void run() {
				System.out.println(i++);
			}
		}, new Date(todayMill), period);
	}

	/**
	 * 自动循环运行
	 */
	public void runAuto() {
		if (!timerSwitch)
			return;
		int delay = 2000;// 第一次延迟
		int period = 1000;// 运行间隔;86400 000day; 3600 000 hour; 60 000 minute
		Timer timer = new Timer();
		timer.scheduleAtFixedRate(new TimerTask() {
			int i = 0;

			// String s = "s";
			public void run() {
				try {// 为防止线程挂掉，异常全部捕抓掉
						// Integer.parseInt(s);
					System.out.println(i++);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}, delay, period);

	}

	/**
	 * 定时器 每周
	 */
	public void runPerWeek() {
		if (!timerSwitchPerWeek)
			return;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String today = sdf.format(new Date());
		Date d = null;
		try {
			d = sdf.parse(today);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		long todayMill = d.getTime() + 7200000;// 凌晨2点
		long period = 86400000*7;// 每周
		Timer timer = new Timer();
		if (System.currentTimeMillis() > todayMill) {// 明天第一次运行
			todayMill = todayMill + period;
		}
		// System.out.println(new Date(todayMill));

		timer.scheduleAtFixedRate(new TimerTask() {
			int i = 0;

			public void run() {
				System.out.println(i++);
			}
		}, new Date(todayMill), period);
	}
}
